package com.itcast.gameforum.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itcast.gameforum.common.dto.EditDto;
import com.itcast.gameforum.common.lang.Result;
import com.itcast.gameforum.entity.Mainposts;
import com.itcast.gameforum.entity.Posts;

import com.itcast.gameforum.entity.User;
import com.itcast.gameforum.service.MainpostsService;
import com.itcast.gameforum.service.PostsService;

import com.itcast.gameforum.service.UserService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 647zyzlq
 * @since 2020-10-26
 */
@RestController
@RequestMapping("/posts/")
public class PostsController {
    @Autowired
    PostsService postsService;

    @Autowired
    UserService userService;

    @Autowired
    MainpostsService mainpostsService;
    @GetMapping("list")
    public Result findAllList()
    {
        List<Posts> list = postsService.list();
        return new Result().succ(list);
    }

    //得到所有回复主帖子
    @GetMapping("{id}")
    public Result getOne(@PathVariable String id)
    {
        List<Posts> post = postsService.list(new QueryWrapper<Posts>().eq("mainid", id).eq("reply",-1));
        Assert.notNull(post,"主帖子不存在");
        return new Result().succ(post);
    }

    //删除主帖子
    @PostMapping("deleteComments")
    public Result deleteComments(@RequestBody Posts posts)
    {
        Mainposts byId=null;
        if(posts.getComments()==1){
            postsService.remove(new QueryWrapper<Posts>().eq("mainid",posts.getMainid()));
             byId = mainpostsService.getById(posts.getMainid());
            mainpostsService.removeById(posts.getMainid());
            return Result.succ(byId.getZoneid());
        }else{
            postsService.remove(new QueryWrapper<Posts>().eq("mainid",posts.getMainid()).eq("reply",posts.getComments()));
            postsService.removeById(posts.getId());
            return Result.succ("成功删除");
        }

    }


    @GetMapping("{id}/{reply}")
    public Result getReply(@PathVariable String id,@PathVariable String reply)
    {
        List<Posts> post = postsService.list(new QueryWrapper<Posts>().eq("reply", reply).eq("mainid",id));
        Assert.notNull(post,"回复不存在");
        return new Result().succ(post);
    }

    @RequiresAuthentication
    @PostMapping("edit")
    public Result edit(@Valid @RequestBody Posts post)
    {
        User user = userService.getOne(new QueryWrapper<User>().eq("id", post.getUserid()));
        Assert.notNull(user,"用户不能为空");

        post.setCreated(LocalDateTime.now());
        postsService.save(post);
        return new Result().succ("添加帖子成功");
    }


}
